package com.cn.wanxi.service.impl;

import com.cn.wanxi.dao.ICompanyDao;
import com.cn.wanxi.dao.impl.CompanyDaoImpl;
import com.cn.wanxi.model.CompanyModel;
import com.cn.wanxi.service.ICompanyService;
import redis.clients.jedis.Jedis;

import java.util.List;

public class CompanyServiceImpl implements ICompanyService {


    //首先查看redis缓存里面是否有数据
//1.有数据就调用里面的数据，   2.没有数据就去数据库调数据
//   当有redis缓存数据修改时，我们需要对redis缓存数据修改重新赋值
//    1.设置过期时间 分钟*秒  jedis.expire("company_id",30*60);
//    2.手动进行删除数据

    @Override
    public CompanyModel findAll() {
        ICompanyDao iCompanyDao=new CompanyDaoImpl();
        CompanyModel companyModel=null;
        Jedis jedis=new Jedis();
        if (jedis.exists("company_id")){
            companyModel=new CompanyModel();
            companyModel.setId(Integer.valueOf(jedis.get("company_id")));
            companyModel.setLogo(jedis.get("company_logo"));
            companyModel.setEmail(jedis.get("company_email"));
            companyModel.setHotline(jedis.get("company_hotline"));
            companyModel.setAddress(jedis.get("company_address"));
            companyModel.setPhone(jedis.get("company_phone"));
            companyModel.setTel(jedis.get("company_tel"));
            companyModel.setLandline(jedis.get("company_landline"));
        }else {
            companyModel=iCompanyDao.findAll();
            jedis.set("company_id",companyModel.getId().toString());
//            设置过期时间
            jedis.expire("company_id",30*60);
            jedis.set("company_logo",companyModel.getLogo());
            jedis.set("company_email",companyModel.getEmail());
            jedis.set("company_hotline",companyModel.getHotline());
            jedis.set("company_address",companyModel.getAddress());
            jedis.set("company_phone",companyModel.getPhone());
            jedis.set("company_tel",companyModel.getTel());
            jedis.set("company_landline",companyModel.getLandline());
        }
        return companyModel;
    }

    @Override
    public CompanyModel findById(int companyid) {
        ICompanyDao iCompanyDao=new CompanyDaoImpl();
        return iCompanyDao.findById(companyid);
    }

    @Override
    public int update(CompanyModel companyModel) {
        ICompanyDao iCompanyDao=new CompanyDaoImpl();
        int count=iCompanyDao.update(companyModel);
        Jedis jedis=new Jedis();
        if (count==1){
//            jedis.flushAll();//清除所有数据库
//            jedis.flushDB();//清除当前数据库
            jedis.del("company_id");//清除id
            jedis.del("company_logo");//清除id
            jedis.del("company_email");//清除id
            jedis.del("company_hotline");//清除id
            jedis.del("company_address");//清除idjedis.del("company_id");//清除id
            jedis.del("company_phone");//清除id
            jedis.del("company_tel");//清除id
            jedis.del("company_landline");//清除id
        }
        return count;
    }
}
